package com.example.testwebview;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.Serializable;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    WebView content_wv;
    Button test_div;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        content_wv = (WebView) findViewById(R.id.content_wv);
        test_div = (Button) findViewById(R.id.test_js);
        content_wv.setWebViewClient(mWebViewClient);
        addWNBJs();
        setSettings(content_wv.getSettings());
        content_wv.loadUrl("file:///android_asset/test.xml");


        test_div.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                content_wv.loadUrl("javascript:htmlTest('" + "你好啊！" + "')");

            }
        });
    }

    private void setSettings(WebSettings webSettings) {
        webSettings.setJavaScriptEnabled(true);
        //解决https中加载不了http图片问题
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            this.content_wv.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        //设置渲染的优先级
//            webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // 开启 DOM storage API 功能
        webSettings.setDomStorageEnabled(true);
//开启 database storage API 功能
        webSettings.setDatabaseEnabled(true);
        String cacheDirPath = getFilesDir().getAbsolutePath() + "wnb_web_cache";
//设置数据库缓存路径
        webSettings.setDatabasePath(cacheDirPath);
//设置  Application Caches 缓存目录
        webSettings.setAppCachePath(cacheDirPath);
//开启 Application Caches 功能
        webSettings.setAppCacheEnabled(true);

        webSettings.setLoadWithOverviewMode(true);
//设置WebView支持JavaScript
        webSettings.setJavaScriptEnabled(true);
//设置可以访问文件
        webSettings.setAllowFileAccess(true);

        //设置缓存
//        if (!NetUtils.isConnected(getActivity())) {
//            webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
//        } else {
//            webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
//        }
//            1.NARROW_COLUMNS：可能的话使所有列的宽度不超过屏幕宽度
//            2.NORMAL：正常显示不做任何渲染
//            3.SINGLE_COLUMN：把所有内容放大webview等宽的一列中
//            this.content_wv.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
//            第一个方法设置webview推荐使用的窗口，设置为true。第二个方法是设置webview加载的页面的模式，也设置为true。
//            this.content_wv.getSettings().setUseWideViewPort(true);
//            this.content_wv.getSettings().setLoadWithOverviewMode(true);


//            this.content_wv.getSettings().setDomStorageEnabled(true);
//            this.content_wv.getSettings().setAppCacheEnabled(true);
    }


    /**
     * 此方法可以让webview用glide加载图片
     */
    private WebViewClient mWebViewClient = new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView webView, String webUrl) {
//            ondeviceready();
            return super.shouldOverrideUrlLoading(webView, webUrl);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            return super.shouldInterceptRequest(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
//            ondeviceready();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {

            super.onPageStarted(view, url, favicon);
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                WebResourceResponse response = null;
                String url = request.getUrl().toString();
                String refrence = request.getRequestHeaders().get("Referer");
                if (!TextUtils.isEmpty(url) && url.startsWith("http")) {
                    if (url.contains("rtmp")) {
                        return super.shouldInterceptRequest(view, request);
                    }
                    if (url.endsWith(".png")) {
                        response = getWebResourceResponse(url, "image/png", ".png", refrence);
                    } else if (url.endsWith(".gif")) {
                        response = getWebResourceResponse(url, "image/gif", ".gif", refrence);
                    } else if (url.endsWith(".jpg")) {
                        response = getWebResourceResponse(url, "image/jepg", ".jpg", refrence);
                    } else if (url.endsWith(".jepg")) {
                        response = getWebResourceResponse(url, "image/jepg", ".jepg", refrence);
                    } else {
                        return super.shouldInterceptRequest(view, request);
                    }
                    return response;
                } else {
                    return super.shouldInterceptRequest(view, request);
                }
            }
            return super.shouldInterceptRequest(view, request);
        }

        private WebResourceResponse getWebResourceResponse(String url, String mime, String style, String refrence) {
            WebResourceResponse response = null;
//            try {
//                //使用Glide下载，便于显示的时候使用
//                FutureTarget<File> future = Glide.with(getActivity())
//                        .load(url).downloadOnly(500, 500);
//                File localfile = future.get();
//                if (localfile.exists()) {
//                    response = new WebResourceResponse(mime, "UTF-8", new FileInputStream(localfile));
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
            return response;
        }
    };

    /**
     * 自定义js方法【图片预览等】
     */
    private void addWNBJs() {
        this.content_wv.addJavascriptInterface(new Object() {

            @JavascriptInterface
            public void gotoAct(String string) {
                Toast.makeText(MainActivity.this, "gotoAct" + string, Toast.LENGTH_SHORT).show();
            }


        }, "myinterface");
    }
}
